package com.feinno.urcs.group.servlet;

import com.feinno.sip.header.ContentType;
import com.feinno.sip.header.Warning;
import com.feinno.sip.header.extensions.AcceptContact;
import com.feinno.sip.message.SipResponse;
import com.feinno.urcs.group.GroupException;
import com.feinno.urcs.group.api.GroupChatService;
import com.feinno.urcs.group.siputils.GroupHeaderUtils;
import com.feinno.urcs.group.siputils.URIUtils;
import com.feinno.urcs.sipservlet.SipServlet;
import com.feinno.urcs.sipservlet.SipServletException;
import com.feinno.urcs.sipservlet.SipServletRequest;
import com.feinno.urcs.types.MobileNo;
import org.helium.framework.annotations.ServiceSetter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by honghao on 8/17/15.
 */
public class SendGroupSmsServlet extends SipServlet {

	@ServiceSetter
	private GroupChatService groupChatService;

	private final static Logger LOGGER = LoggerFactory.getLogger(SendGroupSmsServlet.class);

	@Override
	protected void process(SipServletRequest request) throws SipServletException {
		LOGGER.info("SendGroupSmsServlet begin process... request: {}", request.toString());
		try {
			AcceptContact acceptContact = (AcceptContact) request.getHeader(AcceptContact.NAME);
			MobileNo fromMobileNo = MobileNo.parseFrom(URIUtils.getMobileNo(GroupHeaderUtils.getFromUri(request)));
			if (acceptContact != null) {
				String value = acceptContact.getParameter("+g.3gpp.iari-ref");
				if (!value.equals("urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.mnc000.mcc460.groupmessage")) {
					SipResponse response = request.createResponse(403);
					Warning warning = new Warning();
					warning.setCode(208);
					warning.setAgent("GC-AS");
					warning.setText("Service not authorised");
					response.setHeader(warning);
					request.sendResponse(response);
					return;
				}
				int groupId = GroupHeaderUtils.parseGroupId(request);
				try {
					if (((ContentType)request.getHeader(ContentType.NAME)).getValue().equalsIgnoreCase("text/plain")) {
						groupChatService.sendSms(fromMobileNo, groupId, new String(request.getRawContent(), "UTF-8"));
					} else {
						groupChatService.sendSms(fromMobileNo, groupId, request);
					}
				} catch (GroupException ex) {
					SipResponse response = request.createResponse(ex.getError().getSipCode());
					Warning warning = new Warning();
					warning.setCode(ex.getError().getWarningCode());
					warning.setAgent(ex.getError().getAgent());
					warning.setText(ex.getError().getText());
					response.setHeader(warning);
					request.sendResponse(response);
					return;
				}
				request.sendResponse(202, "Accepted");
			} else {
				request.sendResponse(400);
				return;
			}
		} catch (Exception ex) {
			LOGGER.error("SendGroupSmsServlet error : {}", ex);
			request.sendResponse(500);
			return;
		}
	}

}
